ko.bindingHandlers.koEasyUITextBox = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called when the binding is first applied to an element
        // Set up any initial state, event handlers, etc. here
		var value = ko.utils.unwrapObservable(valueAccessor()); // Get the current value

		$(element).textbox({value:value});		
		
		$(element).textbox({onChange:function(newValue,oldValue)
		{
			if(newValue !== oldValue)
			{
				var value = valueAccessor();
				value(newValue); 
			}			
		}});		
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever any observables/computeds that are accessed change
        // Update the DOM element based on the supplied values here.		
		var value = valueAccessor();
        //if (ko.utils.unwrapObservable(value))
		{
			$(element).textbox('setValue',value());
		}
    }
};

ko.bindingHandlers.koEasyUIComboBox = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called when the binding is first applied to an element
        // Set up any initial state, event handlers, etc. here
		var value = ko.utils.unwrapObservable(valueAccessor()); // Get the current value
		var allBindings=allBindings();
		var option={
						valueField:allBindings.valueField,
						textField:allBindings.textField,
						url:allBindings.url,
						multiple:allBindings.multiple,
						queryParams:allBindings.queryParams,
						data:allBindings.data==null?null:allBindings.data(),
						onLoadSuccess:function()
						{							 
							if(value === '0')
							{
								value='';
							}

							value=value.toString().replace(/,+/ig,',').replace(/^,|,$/ig,'');
							if(allBindings.multiple)
							{
								$(element).combobox('setValues',value.split(','));
							}
							else 
							{								
								$(element).combobox('setValue',value);
							}
						}
					};
	
		$(element).combobox(option);		
		$(element).combobox({onChange:function(newValue,oldValue)
		{
			if(newValue !== oldValue)
			{				
				var value = valueAccessor();
				if(allBindings.multiple)
				{
					value(newValue.join(','));
				} 
				else 
				{
					newValue=newValue.toString().replace(/,+/ig,',').replace(/^,|,$/ig,'');
					value(newValue);
				}
			}			
		}});

		ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $(element).combobox("destroy");
        });		
		
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever any observables/computeds that are accessed change
        // Update the DOM element based on the supplied values here.		
		var allBindings=allBindings();
		var value = valueAccessor();
        //if (ko.utils.unwrapObservable(value))
		{
			value=value().toString().replace(/,+/ig,',').replace(/^,|,$/ig,'');
			if(allBindings.multiple) {
				$(element).combobox('setValues',value.split(','));
			}
			else $(element).combobox('setValue',value);
		}
    }
};

ko.bindingHandlers.koEasyUIDateBox = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var jq = $(element);   
        var value = ko.utils.unwrapObservable(valueAccessor());
        var dateValue = "";
        if (value === "/Date(-62135596800000)/" || value === undefined || value === null) {
            dateValue = "";
        } else {
            dateValue = moment(value).format('YYYY-MM-DD');
            if (dateValue.indexOf("Invalid") > -1) {
                dateValue = "";
            }
        }
        jq.datebox({
            formatter: function(date) {
                if (date !== "") {
                    return moment(date).format('YYYY-MM-DD');
                }
            },
            parser: function(date) {
                if (date !== "") {
                    return new Date(Date.parse(date.replace(/-/g, "/")));
                }
            },
            onSelect: function(date) {
                var value = valueAccessor();
                value(moment(date).format('YYYY-MM-DD'));
            }
        });
        $(element).datebox('setValue', dateValue);
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            jq.datebox("destroy");
        });
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var dateValue = "";
        if (value === "/Date(-62135596800000)/" || value === undefined || value === null) {
            dateValue = "";
        } else {
            dateValue = moment(value).format('YYYY-MM-DD');
            if (dateValue.indexOf("Invalid") > -1) {
                dateValue = "";
            }
        }
        $(element).datebox('setValue', dateValue);
    }
};

ko.bindingHandlers.koEasyUIComboTree = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
		var value = ko.utils.unwrapObservable(valueAccessor()); // Get the current value
		var allBindings=allBindings();
		var option={
					valueField:allBindings.valueField,
					textField:allBindings.textField,
					url:allBindings.url,
					queryParams:allBindings.queryParams,
					multiple:allBindings.multiple,
					data:allBindings.data==null?null:allBindings.data(),
					onLoadSuccess:function()
					{
						if(value === '0')
						{
							value='';
						}
						value=value.toString().replace(/,+/ig,',').replace(/^,|,$/ig,'');
						if(allBindings.multiple)
						{
							$(element).combotree('setValues',value.split(','));
						}
						else 
						{								
							$(element).combotree('setValue',value);
						}
					}
					};
	
		$(element).combotree(option);
		
		$(element).combotree({onChange:function(newValue,oldValue)
		{	
			if(newValue !== oldValue)
			{				
				var value = valueAccessor();
				if(allBindings.multiple)
				{
					value(newValue.join(','));
				} 
				else 
				{
					newValue=newValue.toString().replace(/,+/ig,',').replace(/^,|,$/ig,'');
					value(newValue);
				}
			}	
						
		}});
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever any observables/computeds that are accessed change
        // Update the DOM element based on the supplied values here.		
		var value = valueAccessor();
        //if (ko.utils.unwrapObservable(value))
		{
			value=value().toString().replace(/,+/ig,',').replace(/^,|,$/ig,'');
			if(allBindings.multiple) $(element).combotree('setValues',value.split(','));
			else $(element).combotree('setValue',value);
		}
    }
};

ko.bindingHandlers.koEasyUIComboGrid = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
		var value = ko.utils.unwrapObservable(valueAccessor()); // Get the current value
		var allBindings=allBindings();
		var option={
						idField:allBindings.idField,
						textField:allBindings.textField,
						url:allBindings.url,
						multiple:allBindings.multiple,
						data:allBindings.data==null?null:allBindings.data(),
						columns:[allBindings.columns],
						onLoadSuccess:function()
						{						
							value=value.toString().replace(/,+/ig,',').replace(/^,|,$/ig,'');
							if(allBindings.multiple) {
								$(element).combogrid('setValues',value.split(','));
							}
							else $(element).combogrid('setValue',value);
						}
					};			
	
		$(element).combogrid(option);
		
		$(element).combogrid({onChange:function(newValue,oldValue)
		{
			var value = valueAccessor();			
			if(allBindings.multiple) {
				value(newValue.join(',')); 
			}
			else value(newValue); 
						
		}});
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever any observables/computeds that are accessed change
        // Update the DOM element based on the supplied values here.		
		var value = valueAccessor();
        //if (ko.utils.unwrapObservable(value))
		{
			value=value().toString().replace(/,+/ig,',').replace(/^,|,$/ig,'');
			if(allBindings.multiple) {
				$(element).combogrid('setValues',value.split(','));
			}
			else $(element).combogrid('setValue',value);
		}
    }
};

//绑定富文本编辑框
ko.bindingHandlers.koRichText = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        var txtBoxID = $(element).attr("id");
        if(txtBoxID === undefined || txtBoxID === null || txtBoxID === '')
        {
        	txtBoxID='richText'+Math.random();
        	$(element).attr("id",txtBoxID);
        }
        var instance = CKEDITOR.instances[txtBoxID];
        var options = allBindingsAccessor().richTextOptions || {};
        options.toolbar_Full = [
                ['Source', '-', 'Format', 'Font', 'FontSize', 'TextColor', 'BGColor', '-', 'Bold', 'Italic', 'Underline', 'SpellChecker'],
                ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl'],
                ['Link', 'Unlink', 'Image', 'Table']
            ]
            //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            if (CKEDITOR.instances[txtBoxID]) {
                CKEDITOR.remove(CKEDITOR.instances[txtBoxID]);
            };
        });
        $(element).ckeditor(options);
        //wire up the blur event to ensure our observable is properly updated
        CKEDITOR.instances[txtBoxID].focusManager.blur = function() {
            var observable = valueAccessor();
            observable($(element).val());
        };
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        var element$ = $(element);
        var newValue = ko.utils.unwrapObservable(valueAccessor());
        if (element$.ckeditorGet().getData() !== newValue) {
            var html = htmlDecode(newValue);
            element$.ckeditorGet().setData(html);
        }

        function htmlDecode(html) { //
        	// html=html.replace('&amp;','&');
	        var a = document.createElement('a');
	        a.innerHTML = html;
	        return a.textContent;
    	}

    }
};